package com.example.demo.jpa.service;

import com.example.demo.jpa.dao.UserDAO;
import com.example.demo.jpa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.*;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @author lyc
 * @date 2019/7/4.
 */
@Service
public class UserService {

    @Autowired
    private UserDAO userDAO;

    public List<User> pageList(){
        Sort.Direction direction = Sort.Direction.DESC;
        //Pageable pageable=new PageRequest(1, 10, direction,"name");
        Pageable pageable = PageRequest.of(1, 10, direction,"name");

        userDAO.findAll(new Specification<User>() {
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                Predicate predicate=criteriaBuilder.conjunction();

                //in
                Path<Object> path = root.get("id");
                CriteriaBuilder.In<Object> in = criteriaBuilder.in(path);
                in.value(1);
                in.value(2);
                predicate.getExpressions().add(in);
                //date
                String startDate = "2019-02-04";
                predicate.getExpressions().add(criteriaBuilder.greaterThan(root.get("createTime").as(String.class),startDate));
                predicate.getExpressions().add(criteriaBuilder.lessThan(root.get("createTime"),new Date()));
                //number
                predicate.getExpressions().add(criteriaBuilder.le(root.get("id"),2));

                //or
                String name = "aa";
                predicate.getExpressions().add(criteriaBuilder.or(criteriaBuilder.like(root.get("name"),"%"+name+"%"),criteriaBuilder.le(root.get("id"),2)));

                return predicate;
            }
        },pageable);
        return null;
    }

    List<User> list(String name,User user){
        return null;
    }
}